<template>
  <div class="form-comp">
    <div class="toolbar-item toolbar-select"
         v-if="label"
    >
      <el-input size="default"
                :style="{width:(label.length==2?'68px':label.length==3?'82px':label.length==4?'96px':label.length==7?'138px':label.length==6?'128px':''),float:'left'}">
        <template #prepend>{{ label }}</template>
      </el-input>
      <el-date-picker
          v-model="compValue"
          :type="type"
          size="default"
          :format="dateFormat"
          @change="changeDate"
          :disabled-date="disabledDateEvent"
          start-placeholder="请选择开始日期"
          end-placeholder="请选择结束日期"
          :range-separator="rangeSeparator"
          :class="label.length==3?'prepend-date-3':label.length==4?'prepend-date-4':label.length==5?'prepend-date-5':label.length==6?'prepend-date-6':label.length==7?'prepend-date-7':'prepend-date-2'"
      />
    </div>
    <div v-else>
      <el-date-picker
          v-model="compValue"
          :type="type"
          :disabled="disabled"
          :format="dateFormat"
          :disabled-date="disabledDateEvent"
          start-placeholder="请选择开始日期"
          end-placeholder="请选择结束日期"
          :range-separator="rangeSeparator"
          @change="changeDate"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
//定义组件名称
// @ts-ignore
import {getCurrentInstance, onMounted, ref, watch} from "vue";
// @ts-ignore
import moment from 'moment'

defineOptions({
  name: "FormDatePicker"
});

/**
 * type: week,date,year,month
 */
const props = defineProps({
  label: {type: String, required: false},
  value: {type: String, required: true, default: ''},
  format: {type: String, required: false, default: 'YYYY-MM-DD'},
  disabled: {type: Boolean, required: false},
  type: {type: String, required: false, default: 'date'},
  disabledDate: {type: Boolean, required: false},
  rangeSeparator: {type: String, required: false, default: '~'},
  defaultValue: {type: Boolean, required: false, default: false},
  rangeHour: {type: Number, required: false, default: -24},
  defaultType: {type: String, required: false, default: "date"},
  defaultHour: {type: String, required: false, default: ""},

});

const dateFormat = ref<any>(props.format)

//组件的值
const compValue = ref<any>(props.value);

onMounted(() => {
  callData();
})

const callData = () => {
  if (props.defaultValue) {
    dateFormat.value = props.format
  } else if (props.type === 'date' || props.type === 'daterange') {
    dateFormat.value = "YYYY-MM-DD"
  } else if (props.type === 'week') {
    dateFormat.value = "WW"
  } else if (props.type === 'year') {
    dateFormat.value = "YYYY"
  } else if (props.type === 'month' || props.type === 'monthrange') {
    dateFormat.value = "YYYY-MM"
  } else if (props.type === 'datetime' || props.type === 'datetimerange') {
    dateFormat.value = "YYYY-MM-DD HH:mm:ss"
  }
  if (props.type?.indexOf("range") > -1) {
    compValue.value = [];
    if (props.value) {
      compValue.value.push(props.value?.split(props.rangeSeparator)[0]);
      compValue.value.push(props.value?.split(props.rangeSeparator)[1]);
      console.log(compValue, "compValue");
    } else {
      defaultDateTimeValue();
    }
  } else if (props.value) {
    compValue.value = props.value;
  } else {
    defaultDateTimeValue();
  }

}

watch(() => props.value, () => {
  if (props.value == "") {
    compValue.value = ""
    defaultDateTimeValue();
  } else {
    callData();
  }
})
const emit = defineEmits(['update:value'])

const changeDate = (date: any) => {
  let dateResult = null;
  if (props.type === 'date') {
    dateResult = moment(date).format(dateFormat.value)
  } else if (props.type === 'week') {
    let week = moment(date).format(dateFormat.value?.replace("YYYY", "yyyy").replace("ww", "WW")) //周
    dateResult = parseInt(week)
  } else if (props.type === 'year') {
    dateResult = moment(date).format(dateFormat.value?.toLowerCase())
  } else if (props.type === 'month') {
    dateResult = moment(date).format(dateFormat.value?.replace("YYYY", "yyyy").replace("MM", "MM"));
  } else if (props.type === 'datetime') {
    dateResult = moment(date).format(dateFormat.value)
  } else {
    dateResult = moment(date[0]).format(dateFormat.value) + props.rangeSeparator + moment(date[1]).format(dateFormat.value)
  }

  emit('update:value', dateResult);
}

function getWeek(dateTime: any) {
  let temptTime = dateTime
  //周几
  let weekday = temptTime.getDay() || 7
  console.log(weekday);
  //周1+5天=周六
  temptTime.setDate(temptTime.getDate() - weekday + 1 + 5)
  let firstDay = new Date(temptTime.getFullYear(), 0, 1)
  let dayOfWeek = firstDay.getDay()
  let spendDay = 1
  if (dayOfWeek != 0) {
    spendDay = 7 - dayOfWeek + 1
  }
  firstDay = new Date(temptTime.getFullYear(), 0, 1 + spendDay)
  let d = Math.ceil((temptTime.valueOf() - firstDay.valueOf()) / 86400000)
  let result = Math.ceil(d / 7)
  return (result + 1) + "";
}

const disabledDateEvent = (date: any) => {
  if (props.disabledDate) {
    return date.getTime() > Date.now()
  } else {
    return false;
  }
}

/**
 * 默认时间
 */
const defaultDateTimeValue = () => {
  if (props.defaultValue) {
    const t = new Date();
    let dateResult = null;

    if (props.type === 'datetimerange') {
      const ot = new Date(t.getTime() + (props.rangeHour * 60 * 60 * 1000));
      compValue.value = [];
      compValue.value.push(dateToStr(ot));
      compValue.value.push(dateToStr(t));
      dateResult = moment(dateToStr(ot)).format(props.format) + props.rangeSeparator + moment(dateToStr(t)).format(props.format)
    } else if (props.type === 'date') {
      compValue.value = dateToStr(t);
      dateResult = moment(compValue.value).format(props.format);
    } else if (props.type === 'daterange') {
      const ot = new Date(t.getTime() + (props.rangeHour * 60 * 60 * 1000));
      compValue.value = [];
      compValue.value.push(dateToStr(ot));
      compValue.value.push(dateToStr(t));
      dateResult = moment(dateToStr(ot)).format(props.format) + props.rangeSeparator + moment(dateToStr(t)).format(props.format)
    } else if (props.type === 'datetime') {
      compValue.value = dateToStr(t);
      dateResult = moment(compValue.value).format(props.format);
    }
    emit('update:value', dateResult);
  }

}
const dateToStr = (t: Date) => {
  if (props.defaultType === 'datetime') {
    return t.getFullYear() + "-" + ((t.getMonth() + 1) > 9 ? (t.getMonth() + 1) : ('0' + (t.getMonth() + 1))) + "-" + (t.getDate() > 9 ? t.getDate() : '0' + t.getDate()) + ' ' + (t.getHours() > 9 ? t.getHours() : '0' + t.getHours()) + ":" + (t.getMinutes() > 9 ? t.getMinutes() : '0' + t.getMinutes()) + ":" + (t.getSeconds() > 9 ? t.getSeconds() : '0' + t.getSeconds());
  } else if (props.defaultType === 'date') {
    return t.getFullYear() + "-" + ((t.getMonth() + 1) > 9 ? (t.getMonth() + 1) : ('0' + (t.getMonth() + 1))) + "-" + (t.getDate() > 9 ? t.getDate() : '0' + t.getDate()) + props.defaultHour;
  } else if (props.defaultType === 'datetimeNextHour') {
    return t.getFullYear() + "-" + ((t.getMonth() + 1) > 9 ? (t.getMonth() + 1) : ('0' + (t.getMonth() + 1))) + "-" + (t.getDate() > 9 ? t.getDate() : '0' + t.getDate()) + ' ' + ((t.getHours() + 1) > 9 ? (t.getHours() + 1) : '0' + (t.getHours() + 1)) + ":00:00";
  } else if (props.defaultType === 'dateTimeHour') {
    return t.getFullYear() + "-" + ((t.getMonth() + 1) > 9 ? (t.getMonth() + 1) : ('0' + (t.getMonth() + 1))) + "-" + (t.getDate() > 9 ? t.getDate() : '0' + t.getDate()) + ' ' + (t.getHours() > 9 ? t.getHours() : '0' + t.getHours()) + ":00:00";
  } else if (props.defaultType === 'dateTimeHourMinutes') {
    return t.getFullYear() + "-" + ((t.getMonth() + 1) > 9 ? (t.getMonth() + 1) : ('0' + (t.getMonth() + 1))) + "-" + (t.getDate() > 9 ? t.getDate() : '0' + t.getDate()) + ' ' + (t.getHours() > 9 ? t.getHours() : '0' + t.getHours()) + ":" + (t.getMinutes() > 9 ? t.getMinutes() : '0' + t.getMinutes()) + ":00";
  }
}

</script>

<style scoped>

</style>